package org.example.seckill.util;

import org.example.seckill.bean.User;

import java.sql.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author woopsion
 * @date 2025-07-02
 */
public class RandomUserGenerator {
    // 数据库配置（请根据实际情况修改）
    private static final String DB_URL = "jdbc:mysql://192.168.5.6:3306/seckill";
    private static final String DB_USER = "woopsion";
    private static final String DB_PASSWORD = "hsp8";

    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            int numUsers = 2000; // 要生成的用户数量
            generateAndInsertUsers(conn, numUsers);
            System.out.println("成功插入 " + numUsers + " 个随机用户");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void generateAndInsertUsers(Connection conn, int count) throws SQLException {
        String sql = "INSERT INTO seckill_user (id, password, nickname, slat, head, register_date, last_login_date, login_count) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            for (int i = 0; i < count; i++) {
                User user = generateRandomUser();
                setPreparedStatement(pstmt, user);
                pstmt.executeUpdate();
            }
        }
    }

    private static User generateRandomUser() {
        User user = new User();
        user.setId(Math.abs(ThreadLocalRandom.current().nextLong())); // 生成随机ID
        user.setPassword("123456"); // 模拟MD5密码
        user.setNickname("用户_" + generateRandomString(8));
        user.setSlat(generateRandomString(6)); // 盐值
        user.setHead("https://avatar.example.com/" + generateRandomString(10) + ".jpg");

        // 注册时间（过去1年内随机）
        user.setRegisterDate(generateRandomDate(365));

        // 最后登录时间（50%概率为null，50%在注册时间后随机）
        if (ThreadLocalRandom.current().nextBoolean()) {
            user.setLastLoginDate(generateRandomDateAfter(user.getRegisterDate()));
        } else {
            user.setLastLoginDate(null);
        }

        // 登录次数（0-100）
        user.setLoginCount(ThreadLocalRandom.current().nextInt(0, 101));

        return user;
    }

    private static void setPreparedStatement(PreparedStatement pstmt, User user) throws SQLException {
        pstmt.setLong(1, user.getId());
        pstmt.setString(2, user.getPassword());
        pstmt.setString(3, user.getNickname());
        pstmt.setString(4, user.getSlat());
        pstmt.setString(5, user.getHead());
        pstmt.setTimestamp(6, new Timestamp(user.getRegisterDate().getTime()));
        if (user.getLastLoginDate() != null) {
            pstmt.setTimestamp(7, new Timestamp(user.getLastLoginDate().getTime()));
        } else {
            pstmt.setNull(7, Types.TIMESTAMP);
        }
        pstmt.setInt(8, user.getLoginCount());
    }

    // 辅助方法：生成随机字符串
    private static String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(ThreadLocalRandom.current().nextInt(chars.length())));
        }
        return sb.toString();
    }

    // 辅助方法：生成过去N天内的随机日期
    private static Date generateRandomDate(int daysBack) {
        long offset = ThreadLocalRandom.current().nextLong(daysBack * 24 * 60 * 60 * 1000L);
        return new Date(System.currentTimeMillis() - offset);
    }

    // 辅助方法：生成注册时间之后的随机日期
    private static Date generateRandomDateAfter(Date registerDate) {
        long maxOffset = System.currentTimeMillis() - registerDate.getTime();
        long offset = ThreadLocalRandom.current().nextLong(maxOffset);
        return new Date(registerDate.getTime() + offset);
    }
}
